import ctypes
from ctypes import wintypes

# max user count
XUSER_MAX_COUNT = 4

# buttons
XINPUT_GAMEPAD_DPAD_UP = 0x0001
XINPUT_GAMEPAD_DPAD_DOWN = 0x0002
XINPUT_GAMEPAD_DPAD_LEFT = 0x0004
XINPUT_GAMEPAD_DPAD_RIGHT = 0x0008
XINPUT_GAMEPAD_START = 0x0010
XINPUT_GAMEPAD_BACK = 0x0020
XINPUT_GAMEPAD_LEFT_THUMB = 0x0040
XINPUT_GAMEPAD_RIGHT_THUMB = 0x0080
XINPUT_GAMEPAD_LEFT_SHOULDER = 0x0100
XINPUT_GAMEPAD_RIGHT_SHOULDER = 0x0200
XINPUT_GAMEPAD_A = 0x1000
XINPUT_GAMEPAD_B = 0x2000
XINPUT_GAMEPAD_X = 0x4000
XINPUT_GAMEPAD_Y = 0x8000


class XINPUT_GAMEPAD(ctypes.Structure):
    _fields_ = [
        ('wButtons', wintypes.WORD),
        ('bLeftTrigger', ctypes.c_ubyte),  # wintypes.BYTE is signed
        ('bRightTrigger', ctypes.c_ubyte),  # wintypes.BYTE is signed
        ('sThumbLX', wintypes.SHORT),
        ('sThumbLY', wintypes.SHORT),
        ('sThumbRX', wintypes.SHORT),
        ('sThumbRY', wintypes.SHORT)
    ]


class XINPUT_STATE(ctypes.Structure):
    _fields_ = [
        ('dwPacketNumber', wintypes.DWORD),
        ('Gamepad', XINPUT_GAMEPAD)
    ]


class XINPUT_VIBRATION(ctypes.Structure):
    _fields_ = [
        ('wLeftMotorSpeed', wintypes.WORD),
        ('wRightMotorSpeed', wintypes.WORD)
    ]


def get_state(user_index):
    xinput = ctypes.windll.XInput1_4
    c_state = XINPUT_STATE()
    ret = xinput.XInputGetState(user_index, ctypes.byref(c_state))
    return ret, c_state


def set_state(user_index, vibration_left, vibration_right):
    xinput = ctypes.windll.XInput1_4
    c_vibration = XINPUT_VIBRATION()
    c_vibration.wLeftMotorSpeed = vibration_left
    c_vibration.wRightMotorSpeed = vibration_right
    ret = xinput.XInputSetState(user_index, ctypes.byref(c_vibration))
    return ret

# 需要执行的代码
def main():
    user_index = 0  # 使用第一个控制器
    ret, state = get_state(user_index)
    
    if ret == 0:  # 状态返回值为0表示成功
        print("控制器连接成功")
        
        # 获取按钮状态
        button_state = state.Gamepad.wButtons
        
        # 获取触发器状态
        left_trigger = state.Gamepad.bLeftTrigger
        right_trigger = state.Gamepad.bRightTrigger
        
        # 获取摇杆坐标
        thumbLX = state.Gamepad.sThumbLX
        thumbLY = state.Gamepad.sThumbLY
        thumbRX = state.Gamepad.sThumbRX
        thumbRY = state.Gamepad.sThumbRY
        
        # 输出所有状态信息
        print(f"按钮状态: {button_state}")
        print(f"左触发器状态: {left_trigger}")
        print(f"右触发器状态: {right_trigger}")
        print(f"左摇杆坐标: ({thumbLX}, {thumbLY})")
        print(f"右摇杆坐标: ({thumbRX}, {thumbRY})")
        
    else:
        print(f"控制器连接失败，错误代码: {ret}")

# 执行主函数
if __name__ == "__main__":
    main()
